﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ionic.Zip;
using System.IO;
using System.Xml;

namespace EssaiZipLibApp
{
    /// <summary>
    /// to test the zip lib.
    /// </summary>
    class Program
    {
        public static void SaveToZip(string fileName)
        {
            //string fileName = @"E:\temp\MyProject.zip";

            XmlDocument xmldoc;
            XmlNode xmlnode;
            XmlElement xmlelem;
            XmlElement xmlelem2;
            XmlText xmltext;
            xmldoc=new XmlDocument();
            //let's add the XML declaration section
            xmlnode=xmldoc.CreateNode(XmlNodeType.XmlDeclaration,"","");
            xmldoc.AppendChild(xmlnode);
            //let's add the root element
            xmlelem=xmldoc.CreateElement("","root","");
            xmltext=xmldoc.CreateTextNode("This is the text of the root element");
            xmlelem.AppendChild(xmltext);
            xmldoc.AppendChild(xmlelem);
            //let's add another element (child of the root)
            xmlelem2=xmldoc.CreateElement("","SampleElement","");
            xmltext=xmldoc.CreateTextNode("The text of the sample element");
            xmlelem2.AppendChild(xmltext);
            xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);

            MemoryStream xmlStream = new MemoryStream();
            xmldoc.Save(xmlStream);
            xmlStream.Position = 0;
            
            //StreamReader sr = new StreamReader(xmlStream);
            
            //xmldoc.Save(sr); 

            //StreamReader sr = new StreamReader(
            using (ZipFile zip = new ZipFile())
            {
                ZipEntry e = zip.AddEntry("header.xml", xmlStream);
                zip.Save(fileName);
            }

            //sr.Close();
            xmlStream.Close();
        }

        static void LoadFromZip(string fileName)
        {
            MemoryStream xmlStream = new MemoryStream();
            XmlDocument xmldoc= new XmlDocument();

            using (ZipFile zip = ZipFile.Read(fileName))
            {
                ZipEntry e = zip["header.xml"];
                e.Extract(xmlStream);
                xmlStream.Position = 0;
                xmldoc.Load(xmlStream);
            }
        }

        static void Main(string[] args)
        {
            string fileName = @"E:\temp\MyProject.zip";

            SaveToZip(fileName);
            LoadFromZip(fileName);
        }
    }
}
